import { Component, Input, OnInit } from '@angular/core';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { EventService } from 'src/app/shared/service/event.service';
import { HttpService } from 'src/app/shared/service/http.service';
//tslint:disable

@Component({
  selector: 'app-smooth-style-button',
  templateUrl: './smooth-style-button.component.html',
  styleUrls: ['./smooth-style-button.component.scss'],
})
export class SmoothStyleButtonComponent implements OnInit {
  @Input() tagData;
  index = 0;
  refreshFilterId: any;
  key: any;
  type = "filter";
  switchBlockButtonId = 'SmoothStyleButtonComponentID';
  isSpinning = false;
  currentTags = [];
  defaultTabClass = 'overFlowdefault';
  boxCssStyle = '';
  isGrayBg = false;
  notInContent = false;
  contentScrollEvents = false;
  // result: any = { showName: "", filter: {}, order: {} };
  constructor(
    private httpService: HttpService,
    private ags: AppGlobalService,
    private eventService: EventService
  ) {
    this.eventService.eventEmit.on("smoothTabChangeByIndex", (tabIndex) => {
      if (tabIndex) {
        this.index = tabIndex;
        const id = this.tagData.data[tabIndex].tabType;
        if (document.getElementById(id)) {
          document.getElementById(id).click();
        }
      }
    });
  }

  ngOnInit() {
    this.eventService.removeCustomListListeners();
    this.switchBlockButtonId += new Date().getTime();
    this.currentTags = this.tagData.currentData.tags;
    this.isGrayBg = this.tagData.currentData.isGrayBg;
    if (this.tagData && this.tagData.data.length > 0) {

      this.tagData.data.forEach(element => {
        if (element.indexTab !== undefined && typeof (element.indexTab) === 'number') {
          element.indexTab += '';
        }
      });

      this.ags.scListTagName = this.tagData.data[0].listTagName;
      if (this.tagData.data[0].partLink.params) {
        if (this.tagData.data[0].partLink.params.scroll) {
          this.defaultTabClass = this.tagData.data[0].partLink.params.scroll;

        }
        if (this.tagData.data[0].partLink.params.boxCssStyle) {
          this.boxCssStyle = this.tagData.data[0].partLink.params.boxCssStyle;
        }
        if (this.tagData.data[0].partLink.params.contentScrollEvents) {
          this.contentScrollEvents = this.tagData.data[0].partLink.params.contentScrollEvents;
        }
        if (this.tagData.data[0].partLink.params.notInContent) {
          this.notInContent = this.tagData.data[0].partLink.params.notInContent;
        }



      }

      if (this.tagData.data[0].params) {
        const paramKeys = Object.keys(this.tagData.data[0].params);
        for (let j = 0; j < paramKeys.length; j++) {
          const keyName = paramKeys[j];
          if (keyName !== 'filter') {
            const newParamObj = {};
            newParamObj[keyName] = this.tagData.data[0].params[keyName];
            Object.assign(this.ags.scResult, newParamObj);
          } else if (keyName === "filter") {
            this.ags.scResult.filter = this.tagData.data[0].params.filter;
          }
        }
      }
    }


    // if (localStorage.getItem('subTab_index')) {
    //   const subTabIndex = localStorage.getItem('subTab_index');

    //   localStorage.removeItem('subTab_index');
    //   setTimeout(() => {
    //     if (this.tagData.currentTab !== subTabIndex) {
    //       const id = this.tagData.data[parseInt(subTabIndex)].tabType;
    //       if (document.getElementById(id)) {
    //         document.getElementById(id).click();
    //       }
    //     }
    //   }, 300);
    // }
  }


  // 为了不影响之前的使用 使用新的属性
  newSwitchBlockClick(dateIndex, item) {
    // loop 取数据则从-1或者-2开始 1.9.0 改动版本   
    if (parseInt(this.tagData.data[0] && this.tagData.data[0].indexTab) < 0) {
      dateIndex--;
    }
    this.tagData.currentTab = dateIndex + '';
    try {
      item.selected = 'true';
      this.requestData(item);
    } catch (error) {
    }
  }



  switchBlockClick(item, className, itemIndex) {

    if (this.tagData.data[itemIndex].partLink.params) {
      if (this.tagData.data[itemIndex].partLink.params.scroll) {
        this.defaultTabClass = this.tagData.data[itemIndex].partLink.params.scroll;
      }
      if (this.tagData.data[itemIndex].partLink.params.boxCssStyle) {
        this.boxCssStyle = this.tagData.data[itemIndex].partLink.params.boxCssStyle;
      }
      if (this.tagData.data[itemIndex].partLink.params.contentScrollEvents) {
        this.contentScrollEvents = this.tagData.data[itemIndex].partLink.params.contentScrollEvents;
      }
      if (this.tagData.data[itemIndex].partLink.params.notInContent) {
        this.notInContent = this.tagData.data[itemIndex].partLink.params.notInContent;
      }
    }
    this.eventService.removeCustomListListeners();
    if (item.params && item.params.plugin_type_id !== undefined && item.params.plugin_type_id !== item.params.filter.opportunity_plugin_id) {
      item.params.filter.opportunity_plugin_id = item.params.plugin_type_id;
    }
    this.index = itemIndex;
    try {
      item.selected = 'true';
      const nameId = 'smooth-style-button-' + className + this.index;
      const array = document.getElementsByClassName(nameId);
      for (let index = 0; index < array.length; index++) {
        const element = array[index];
        if (item.tabType === element.id) {
          console.log('item.selected.index=========:' + index);
          localStorage.setItem('smoothIndexRecommendTab', index + '');
          // item.check = 1;
          this.addClass(element, "smooth-checked-" + className);
          this.addClass(element.children[0], "smooth-checked-font-" + className);
          if (item.params) {
            const paramKeys = Object.keys(item.params);
            for (let j = 0; j < paramKeys.length; j++) {
              const keyName = paramKeys[j];
              if (keyName !== 'filter') {
                const newParamObj = {};
                newParamObj[keyName] = item.params[keyName];
                Object.assign(this.ags.scResult, newParamObj);
              } else if (keyName === "filter") {
                this.ags.scResult.filter = item.params.filter;
              }
            }
          }
        } else {
          // item.check = 0;
          this.removeClass(element, "smooth-checked-" + className);
          this.removeClass(element.children[0], "smooth-checked-font-" + className);
        }
      }
      this.requestData(item);
    } catch (error) {

    }
  }
  requestData(item) {
    try {
      const params = {
        viewId: item.partLink.target,
        sessionId: localStorage.getItem("sessionId"),
        params: item.partLink.params
      };
      this.isSpinning = true;
      this.httpService.post("application/part", params, res => {
        if (res) {
          const tmpData = JSON.parse(res.script);
          this.tagData.currentData = tmpData;
          this.currentTags = tmpData.tags;
          // console.log(tmpData);
          this.isSpinning = false;
          this.isGrayBg = tmpData.isGrayBg;
        }
      }, err => {
        console.log('error----->' + JSON.stringify(err));
      });
    } catch (error) {
    }
  }

  addClass(ele, value) {
    if (value) {
      let curValue = this.getClass(ele);
      if (curValue.indexOf(value) === -1) {
        curValue = curValue + " " + value;
      }
      ele.setAttribute("class", curValue.trim());
    }
  }
  getClass(elem) {
    return elem.getAttribute && elem.getAttribute("class") || "";
  }
  removeClass(ele, value) {
    if (value) {
      let curValue = this.getClass(ele);
      if (curValue.indexOf(value) > -1) {
        curValue = (" " + curValue + " ").replace(" " + value + " ", " ");
      }
      ele.setAttribute("class", curValue.trim());
    }
  }
  hasClass(ele, value) {
    let has = false;
    if (value) {
      const curValue = this.getClass(ele);
      if (curValue.indexOf(value) > -1) {
        has = true;
      }
    }
    return has;
  }
  // getResult(obj, commonFilterTag, listTagName) {
  //   const pos = JSON.parse(localStorage.getItem("position"));
  //   this.ags.scResult.showName = sessionStorage.getItem('showName') ?
  //     sessionStorage.getItem('showName') : commonFilterTag.keyTag;
  //   const kFilter = "filter";
  //   const kType = "filter";
  //   const kOrder = "order";
  //   const kLocation = "location";
  //   const kStrSort = "sort";
  //   if (this.type === "filter") {
  //     if (obj.min !== undefined || obj.max !== undefined) {
  //       (obj.min === undefined || obj.min === null) ? obj.min = "0" : obj.min = obj.min;
  //       // 用户输入了最小值如果手动删除最大值已与产品沟通传空串
  //       this.ags.scResult[kFilter][this.key] = obj.min + "," + (obj.max === undefined ? "" : obj.max === null ? "" : obj.max);
  //     } else {
  //       this.ags.scResult[kFilter][this.key] = obj.value;
  //     }
  //   } else if (this.type === kOrder) {
  //     if (this.ags.scResult[kLocation]) {
  //       delete this.ags.scResult[kLocation];
  //     }
  //     const kSort = {};
  //     if (obj.value !== undefined) {
  //       obj.value.forEach(v => {
  //         kSort[v.field] = v.value;
  //       });
  //       this.ags.scResult[kOrder][kStrSort] = kSort;
  //     }
  //   }
  //   Object.keys(this.ags.scResult).forEach(element => {
  //     if (element !== 'order') {
  //       if (this.ags.scResult[element] === null) { delete this.ags.scResult[element]; }
  //     }
  //   });
  //   setTimeout(() => {
  //     localStorage.setItem(listTagName + 'AskForListTag', listTagName);
  //     this.eventService.eventEmit.emit(listTagName + 'AskForList', this.ags.scResult);
  //   }, 20);
  // }

}
